﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OBUActivation.Tags;
using OBUActivation.Comm;

namespace OBUActivation
{
    public partial class Form1 : Form
    {

        /// <summary>
        /// 缓存
        /// </summary>
        List<byte> buffer = new List<byte>();

        /// <summary>
        /// BLE串口数据操作类
        /// </summary>
        private BlePortData blePortData;


        public Form1()
        {
            InitializeComponent();

            //线程安全检查初始值设置为默认false
            CheckForIllegalCrossThreadCalls = false;

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public void AppendInfoText(string text){

            if (Communication.Text.ToString().Length == 0)
                Communication.Text = text;
            else
                Communication.Text += System.Environment.NewLine + text;
                Communication.SelectionStart = Communication.Text.Length;
                Communication.ScrollToCaret();
         
        }

        private void ClearButton_Click(object sender, EventArgs e)
        {
            Communication.Text = null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            blePortData = new BlePortData(this, BleCOM.Text.ToString(), 115200);
            blePortData.Open();
            blePortData.Received += new PortDataReceivedEventHandle(BleSerialPort_DataReceived);
            AppendInfoText("蓝牙初始化成功！");

        }

        /// <summary>
        /// 蓝牙串口绑定端口数据接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BleSerialPort_DataReceived(object sender, PortDataReciveEventArgs e)
        {
            try
            {
                byte[] full = null;
                const byte frameFlag = 0xFF;
                // 截取出一整帧的数据
                buffer.AddRange(e.Data);
                int cur = 0;
                int start = 0;
                while (true)
                {
                    if (buffer.Count <= 1) break;
                    if (cur >= buffer.Count - 1) break;
                    if (buffer[cur] == frameFlag && buffer[cur + 1] == frameFlag)
                    {
                        start = cur;
                        cur += 2;
                        while (cur < buffer.Count)
                        {
                            if (buffer[cur] != frameFlag)
                                cur++;
                            else
                            {
                                full = new byte[cur - start + 1];
                                buffer.CopyTo(start, full, 0, full.Length);
                                buffer.RemoveRange(start, cur - start + 1);
                            }
                        }
                        break;
                    }
                    else
                        cur++;
                }
                if (full == null) return;
                BLEMsgRecv(full);
            }
            catch (Exception ex)
            {
                AppendInfoText("发生异常" + ex);
                buffer.Clear();
            }
        }

        //BLE串口数据解析
        private void BLEMsgRecv(byte[] fullmsg)
        {
            byte[] tmp = Tags.CommonFunc.RemoveHeadEnd(fullmsg);
            if (fullmsg[2] == Tags.BaseMsg.cmd_BST5)
            {//解析BST5数据
                Tags.BST5 bst5 = new Tags.BST5();
                bst5.getBST5(tmp);
                if (bst5.BstIsBST5())

                {
                    //获取合同序列号及随机数
                    byte[] conNum = ESAMProgress.GetContractNum();
                    byte[] rnd = ESAMProgress.Get2Random();

                    //返回VST5
                    Tags.VST5 vst5 = new Tags.VST5(conNum,rnd);
                    byte[] msgbody = vst5.toByteArray();
                    byte[] fullMsg = CommonFunc.PackageMsg(msgbody);
                    blePortData.SendBleRawByteArrayData(fullMsg);
                }

            }
        }
    }
}
